package com.century.sjt.activity;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.util.Base64Utils;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TimeButton;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

public class Forget_pwdPayActivity extends BaseActivity{

   // private GridPasswordView newPwd;
    private SjtTitleBar titleBar;
    private RequestQueue mQueue;
    private EditText aPhome,Number_YZ,newPayPassword;
    private Button Btn_Subimt;
    private TimeButton getVCode;
    private String password,smsVCode;
    private String mobile="";
    private Boolean isOK=false;
    private TextView forget_pwd_pnone_icon, forget_yzm_icon, forget_new_pwd_icon;//area_icon;
    //private LinearLayout layout_Country;
    //private TextView tvCountryName;
    private String countryNumber = "86";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_paypwd_forget);
        initView();
        getVCode.onCreate(savedInstanceState);
        initEvent();

    }

    //加载页面
    @Override
    protected void initView() {
        //newPwd=(GridPasswordView) findViewById(R.id.paypwdf_new);
        newPayPassword= (EditText) findViewById(R.id.pwdf_newpaypwd);
        aPhome=(EditText) findViewById(R.id.paypwdf_phone);
        Number_YZ=(EditText) findViewById(R.id.paypwdf_yzm);
        Btn_Subimt=(Button) findViewById(R.id.btn_payf_submit);
        getVCode=(TimeButton) findViewById(R.id.btn_get_payf_check);
        titleBar = (SjtTitleBar) findViewById(R.id.set_pay_forget_title);
        mQueue = Volley.newRequestQueue(this);
        //layout_Country = (LinearLayout) findViewById(R.id.layout_country);
//        tvCountryName = (TextView) findViewById(R.id.country);
//        tvCountryName.setText(getString(R.string.text_china));
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        forget_pwd_pnone_icon = (TextView) findViewById(R.id.forget_pwd_pnone_icon);
        forget_yzm_icon = (TextView) findViewById(R.id.forget_yzm_icon);
        forget_new_pwd_icon = (TextView) findViewById(R.id.forget_new_pwd_icon);
       // area_icon= (TextView) findViewById(R.id.area_icon);
        forget_pwd_pnone_icon.setTypeface(iconfont);
        forget_yzm_icon.setTypeface(iconfont);
        forget_new_pwd_icon.setTypeface(iconfont);
       // area_icon.setTypeface(iconfont);

    }

    @Override
    protected void initEvent() {
        SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        mobile =mainSharedPreferences.getString("mobile", "");
        aPhome.setText(mobile.substring(0,3)+" **** "+mobile.substring(mobile.length()-4,mobile.length()));


        //       标题栏
        titleBar.setLeftIconResource(getResources().getString(R.string.icon_return));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleBar.setTitle(getResources().getString(R.string.tab_forgetpaypwd));
        Btn_Subimt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (LocalValid()){
                    forgetPassWard();
                }
            }
        });
        getVCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVCode.setStart(true);
                smsVcode(mobile);
            }

        });

//        layout_Country.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//                intent.setClass(Forget_pwdPayActivity.this, ChooseCountryActivity.class);
//                startActivityForResult(intent, Constant.REQUESTCODE_COUNTRY);
//            }
//        });

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                Bundle bundle = data.getExtras();
                String str = bundle.getString("countryName");//str即为回传的值
                String mobileCode = bundle.getString("mobileCode");
                countryNumber = mobileCode;
                //tvCountryName.setText(str);
                // tvCountryNumber.setText("+" + mobileCode);
                aPhome.setText("");
                break;
            default:
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void initData() {

    }


    /**
     * 本地验证
     *
     */
    public Boolean LocalValid() {

       // password = newPwd.getPassWord();
        password = newPayPassword.getText().toString();
        smsVCode = Number_YZ.getText().toString();

        if (mobile.equals("")) {
            TipUtil.showToast(getResources().getString(R.string.error_no_phone), Forget_pwdPayActivity.this, 1);
        } else if (password.equals("")||password.length()!=6) {
            TipUtil.showToast(getResources().getString(R.string.error_no_new_password), Forget_pwdPayActivity.this, 1);
        }
        else if (smsVCode.length() < 4) {
//            TipUtil.showToast(getResources().getString(R.string.code_defeat), Forget_pwdPayActivity.this, 1);
        }else {
            isOK=true;
        }
        return isOK;
    }
    //忘记密码

    private void forgetPassWard() {

        byte[] encodePwd = password.getBytes();
        final String npwd = Base64Utils.encode(encodePwd);

        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), Forget_pwdPayActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.ResetPayPassWord, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取成功", response.toString(), 1);

                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        finish();
                    } else {//失败
                        TipUtil.showToast(message, Forget_pwdPayActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), Forget_pwdPayActivity.this, 1);
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), Forget_pwdPayActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("mobile",mobile.trim());
                map.put("password", npwd.trim());
                map.put("validCode",smsVCode.trim());
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }


    /**
     * 获取短信校验码方法
     *
     */
    private void smsVcode(final String mobile) {

//        final String sendphone = mobile;
        //发送短信验证码至服务器进行校验
        //填写了6位数字
        getVCode.setTextAfter(getResources().getString(R.string.btn_second)).setTextBefore(getResources().getString(R.string.btn_get_verification_code)).setLenght(60*1000);//设置倒计时
        //发送短信验证码至服务器进行校验
        //填写了6位数字
        StringRequest regStringRequest = new StringRequest(Request.Method.POST, Constant.SendAuthCode, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取短信校验码接口返回", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//校验成功，进行注册

                        TipUtil.showToast(getResources().getString(R.string.error_smsvcode_success), Forget_pwdPayActivity.this, 1);
                        getVCode.OnStart();
                    } else {
                        TipUtil.showToast(message, Forget_pwdPayActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    //关闭进度条
                    TipUtil.closeProgressDialog();
                    TipUtil.showToast(getResources().getString(R.string.error_service), Forget_pwdPayActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), Forget_pwdPayActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("mobile",mobile);

                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(regStringRequest);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        mQueue.cancelAll(this);
        super.onDestroy();
    }

}
